<template>
	<view class="qh-image" :style="boxStyle">
		<slot name="empty" v-if="isEmpty"></slot>
		<image v-if="!isEmpty" class="image" :src="imageUrl" @error="errorHandler($event)" @click="previewImg"></image>
	</view>
</template>

<script>
	export default {
		name: 'qh-image',
		props: {
			src: {
				type: String,
			}, //图片地址
			defaultUrl: {
				type: String,
				default: '',
			}, //默认图片地址
			shape: {
				type: String,
				default: 'square',
			}, //形状 circle圆形  square方形
			radius: {
				type: String,
				default: '',
			}, //圆角（仅对方形有效）  如：8rpx或8  不传单位默认为rpx
			size: {
				type: [String, Number],
				default: '',
			}, //大小  如：100rpx或100  不传单位默认为rpx
			width: {
				type: String,
				default: '',
			}, //宽  传此值时size失效
			height: {
				type: String,
				default: '',
			}, //高  传此值时size失效
			preview: {
				type: Boolean,
				default: false,
			}, //是否支持预览
			border: {
				type: Boolean,
				default: false,
			}, //是否含有外边框
			borderColor: {
				type: String,
				default: '',
			}, //外边框颜色
		},
		data() {
			return {
				imageUrl: '',
				isEmpty: false,
			}
		},
		computed: {
			boxStyle() {
				let radius = this.shape == 'square' ? (this.radius ? (this.$getUnitSize(this.radius)) : '') : '50%';
				let size = this.$getUnitSize(this.size);
				let width = this.width ? this.$getUnitSize(this.width) : size;
				let height = this.height ? this.$getUnitSize(this.height) : size;

				let obj = {};
				if (width) obj.width = width;
				if (height) obj.height = height;
				if (radius) obj['border-radius'] = radius;

				if (this.border && this.borderColor) obj['border'] = ('2rpx solid ' + this.borderColor);

				return this.$joinStyle(obj);
			},
		},
		methods: {
			errorHandler(e) {
				// console.error('errorHandler', e)
				if (this.imageUrl == this.defaultUrl || !this.defaultUrl) {
					this.isEmpty = true
				} else {
					this.imageUrl = this.defaultUrl;
				}
			},
			//图片预览
			previewImg() {
				if (!this.preview) return;
				uni.previewImage({
					current: 0,
					urls: [this.imageUrl],
				});
			},
			//处理错误图片或空图片
			handleImage() {
				if (!this.src && !this.defaultUrl) {
					this.isEmpty = true;
				} else {
					this.imageUrl = this.src ? this.src : this.defaultUrl;
					this.isEmpty = false;
				}
			},
		},
		created() {
			this.handleImage();
		},
		watch: {
			src(n, o) {
				this.handleImage();
			},
			defaultUrl() {
				this.handleImage();
			}
		}
	}
</script>

<style lang="scss">
	.qh-image {
		width: 100rpx;
		height: 100rpx;
		overflow: hidden;
		box-sizing: border-box;

		.image {
			width: 100%;
			height: 100%;
			//background: #fff;
		}
	}
</style>
